package com.googlecode.restitory.gae.rhino;

import java.io.CharArrayReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import com.googlecode.mycontainer.commons.io.IOUtil;

public class RhinoSandbox extends ScriptableObject {

	private static final long serialVersionUID = -1318212693842489367L;

	private static final RhinoSandbox ME = new RhinoSandbox();

	private RhinoSandbox() {

	}

	public static RhinoSandbox instance() {
		return ME;
	}

	public Object load(URL url) {
		Context cx = Context.enter();
		try {
			RhinoGlobal scope = new RhinoGlobal();
			cx.initStandardObjects(scope);
			ScriptableObject.defineClass(scope, RhinoLog.class);
			Scriptable console = cx.newObject(scope, "Console");
			scope.put("console", scope, console);

			scope.defineFunctionProperties(new String[] { "ping" },
					RhinoGlobal.class, 0);

			char[] chars = IOUtil.readChars(url);
			return cx.evaluateReader(scope, new CharArrayReader(chars),
					url.toString(), 0, null);

		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			Context.exit();
		}
	}

	@Override
	public String getClassName() {
		return "Global";
	}

}
